package com.techwells.applicationMarket.util.swtc;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.google.gson.Gson;
import com.techwells.applicationMarket.exception.GlobalException;
import com.techwells.applicationMarket.util.HttpUtils;



/**
 * 井通钱包的工具类
 * @author 陈加兵
 *
 */
public class SwtcUtils {
	public final static String HTTP="https://api.jingtum.com/";   //调用的IP
	
	/**
	 * 	获取余额
	 * @param address  钱包的地址
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> getBalance(String address) throws Exception{
		String url=HTTP+"v2/accounts/"+address+"/balances";   //查询的余额的api
		return HttpUtils.doGet(url);
	}
	
	
	/**
	 * 获取指定币种的余额
	 * @param address  钱包的地址
	 * @param currency 币种的类型 ，比如SWT和JSLASH
	 * @return 如果返回null表示该地址不支持此币种
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String getBalanceByCurrency(String address,String currency) throws Exception {
		String url=HTTP+"v2/accounts/"+address+"/balances?currency="+currency;   //查询的余额的api
		Map<String, Object> map = HttpUtils.doGet(url);
		// 如果查询失败，直接返回错误信息
		if ((Boolean) map.get("success") == false) {
			throw new GlobalException("-1", "查询失败，请检查钱包地址是否正确");
		}
		
		List<Map<String, Object>> balances = (List<Map<String, Object>>) map
				.get("balances");
		
		String balanceSwt=null;
		// 遍历数组
		for (Map<String, Object> m : balances) {
			if (m.get("currency").equals(currency)) {
				balanceSwt = (String) m.get("value");
				break; // 跳出即可，不必循环了
			}
		}
		return balanceSwt;
	}
	
	
	
	/**
	 * 支付,相当于转账
	 * @param payNeedData 支付信息的封装类
	 * @param fromAddress  支付方的钱包地址
	 * @return
	 * @throws IOException 
	 * @throws ClientProtocolException
	 * 
	 */
	public static Map<String, Object> pay(PayNeedData payNeedData,String fromAddress)throws Exception{
		String jsonParams=new Gson().toJson(payNeedData);  //转换成json字符串的形式
		System.err.println(jsonParams);   //输出json格式的字符串
		String url=HTTP+"v2/accounts/"+fromAddress+"/payments";  //支付的url
		return HttpUtils.doPostReturnMap(url,jsonParams);
	}
	
	
	/**
	 * 币种转账
	 * @param fromAddress  发起方
	 * @param secret      秘钥
	 * @param toAddress  目标方
	 * @param value    金额
	 * @param currency   币种的类型 ，比如SWT和JSLASH
	 * @param issuer   发行人   比如JSLASH的发行人是 jGa9J9TkqtBcUoHe2zqhVFFbgUVED6o9or
	 * @param orderNum
	 * @return
	 * @throws Exception
	 */
	public static String payByCurrency(String fromAddress, String secret, String toAddress, String value,
			String currency, String issuer, String orderNum)throws Exception{
		String url=HTTP+"v2/accounts/"+fromAddress+"/payments";  //支付的url
		PayNeedData data=new PayNeedData();
		//订单号
		data.setClient_id(orderNum);   
		//秘钥
		data.setSecret(secret);  
		
		PayObject payObject=new PayObject();
		//目标账号
		payObject.setDestination(toAddress);   
		//发起账号
		payObject.setSource(fromAddress);  
		
		//转账的金额
		Amount amount=new Amount();
		//金额
		amount.setValue(value);
		//币种类型
		amount.setCurrency(currency);
		//币种的issuer
		amount.setIssuer(issuer);
		
		payObject.setAmount(amount);
		
		data.setPayment(payObject);
		
		
		//调用转账接口
		Map<String, Object> map=SwtcUtils.pay(data,fromAddress);
		
		//转账失败
		if (map==null) {
			throw new GlobalException("-1", "转账失败");
		}
		
		System.out.println(map.get("success"));
		System.out.println(map.get("result"));
		
		if ((Boolean)map.get("success")!=true||!(map.get("result").equals("tesSUCCESS"))) {
			throw new GlobalException("-1", "转账失败");
		}
		
		//转账成功
		String hash=(String) map.get("hash");  //获取hash值，用于查询交易信息
		return hash;
	}
	
	
	
	/**
	 * 查询交易记录
	 * @param hash  交易的hash值
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> getTransaction(String hash) throws Exception{
		String url=HTTP+"v2/transactions/"+hash;  //查询的地址
		return HttpUtils.doGet(url);
	}
	
	
	
	/**
	 * 将指数形式的字符串转换成数值
	 * @param value  
	 * @return
	 */
    public static String formatFloatNumber(Double value) {
        if(value != null){
            if(value.doubleValue() != 0.00){
                java.text.DecimalFormat df = new java.text.DecimalFormat("########");
                return df.format(value.doubleValue());
            }else{
                return "0.00";
            }
        }
        return "";
    }
    
    
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
